<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateChannelAPIRequest;
use App\Http\Requests\API\UpdateChannelAPIRequest;
use App\Http\Requests\API\CreateChannelManagerAPIRequest;
use App\Models\Channel;
use App\Models\Cooperation;
use App\Repositories\ChannelRepository;
use App\Http\Requests\API\CreateChannelOrderAPIRequest;
use App\Repositories\ChannelOrderRepository;
use App\Repositories\HouseRepository;
use App\Repositories\ItemRepository;
use App\Repositories\ChannelVisitDayRepository;
use App\Repositories\ChannelVisitUserRepository;
use App\Repositories\WechatUserRepository;
use App\Repositories\ChannelManagerRepository;
use App\Repositories\ChannelUserRepository;
use App\Repositories\ChannelUserItemRepository;
use App\Repositories\CooperationRepository;
use App\Repositories\ItemOrderRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class ChannelController
 * @package App\Http\Controllers\API
 */

class ChannelAPIController extends AppBaseController
{
    /** @var  ChannelRepository */
    private $channelRepository;

    public function __construct(ChannelRepository $channelRepo)
    {
        $this->channelRepository = $channelRepo;
    }

    /**
     * @param Request $request
     * @return Response
     *
     * @SWG\Get(
     *      path="/channels",
     *      summary="Get a listing of the Channels.",
     *      tags={"Channel"},
     *      description="Get all Channels",
     *      produces={"application/json"},
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="array",
     *                  @SWG\Items(ref="#/definitions/Channel")
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function index(Request $request)
    {
        $this->channelRepository->pushCriteria(new RequestCriteria($request));
        $this->channelRepository->pushCriteria(new LimitOffsetCriteria($request));
        $channels = $this->channelRepository->orderBy('id', 'desc')->simplePaginate($request->input('limit', 20));
        foreach ($channels as $key => $val)
        {
            $channels[$key]->logo_path = $val->logo;
            $channels[$key]->logo = fileUrl($val->logo);
            $channels[$key]->official_account_qrcode_path = $val->official_account_qrcode;
            $channels[$key]->official_account_qrcode = fileUrl($val->official_account_qrcode);
        }

        return $this->sendResponse($channels->toArray(), trans('flash.api.retrieve_success', ['model' => 'Channels']));
    }

    /**
     * @param CreateChannelAPIRequest $request
     * @return Response
     *
     * @SWG\Post(
     *      path="/channels",
     *      summary="Store a newly created Channel in storage",
     *      tags={"Channel"},
     *      description="Store Channel",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="Channel that should be stored",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/Channel")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Channel"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function store(CreateChannelAPIRequest $request)
    {
        $input = $request->all();
        if (isset($input['logo']) && ! fileUrlExists($input['logo']))
        {
            return $this->sendError('logo 图片不存在');
        }

        if (isset($input['official_account_qrcode']) && ! fileUrlExists($input['official_account_qrcode']))
        {
            return $this->sendError('二维码图片不存在');
        }

        $channels = $this->channelRepository->create($input);
        $channels->logo_path = $channels->logo;
        $channels->logo = fileUrl($channels->logo);
        $channels->official_account_qrcode_path = $channels->official_account_qrcode;
        $channels->official_account_qrcode = fileUrl($channels->official_account_qrcode);

        return $this->sendResponse($channels->toArray(), trans('flash.api.save_success', ['model' => 'Channel']));
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Get(
     *      path="/channels/{id}",
     *      summary="Display the specified Channel",
     *      tags={"Channel"},
     *      description="Get Channel",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Channel",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Channel"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function show($id, Request $request,
        ChannelVisitDayRepository $channelVisitDayRepo,
        ChannelVisitUserRepository $channelVisitUserRepo)
    {
        /** @var Channel $channel */
        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channel->logo_path = $channel->logo;
        $channel->logo = fileUrl($channel->logo);
        $channel->official_account_qrcode_path = $channel->official_account_qrcode;
        $channel->official_account_qrcode = fileUrl($channel->official_account_qrcode);

        return $this->sendResponse($channel->toArray(), trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    /**
     * @param int $id
     * @param UpdateChannelAPIRequest $request
     * @return Response
     *
     * @SWG\Put(
     *      path="/channels/{id}",
     *      summary="Update the specified Channel in storage",
     *      tags={"Channel"},
     *      description="Update Channel",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Channel",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="Channel that should be updated",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/Channel")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Channel"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function update($id, UpdateChannelAPIRequest $request)
    {
        $input = $request->all();
        if (isset($input['logo']) && ! fileUrlExists($input['logo']))
        {
            return $this->sendError('logo 图片不存在');
        }

        if (isset($input['official_account_qrcode']) && ! fileUrlExists($input['official_account_qrcode']))
        {
            return $this->sendError('二维码图片不存在');
        }

        /** @var Channel $channel */
        $channel = $this->channelRepository->findWithoutFail($id);

        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channel = $this->channelRepository->update($input, $id);
        $channel->logo_path = $channel->logo;
        $channel->logo = fileUrl($channel->logo);
        $channel->official_account_qrcode_path = $channel->official_account_qrcode;
        $channel->official_account_qrcode = fileUrl($channel->official_account_qrcode);

        return $this->sendResponse($channel->toArray(), trans('flash.api.update_success', ['model' => 'Channel']));
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Delete(
     *      path="/channels/{id}",
     *      summary="Remove the specified Channel from storage",
     *      tags={"Channel"},
     *      description="Delete Channel",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Channel",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="string"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function destroy($id)
    {
        /** @var Channel $channel */
        $channel = $this->channelRepository->findWithoutFail($id);

        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channel->delete();

        return $this->sendResponse($id, trans('flash.api.delete_success', ['model' => 'Channel']));
    }

    public function storeOrders($id,
        CreateChannelOrderAPIRequest $request,
        ChannelOrderRepository $channelOrderRepo,
        HouseRepository $houseRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            $unionidSession = $this->checkWeachtUserByUnionid($request);
        }

        if (isset($e) && ! $unionidSession)
        {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $input = $request->all();
        $input['channel_id'] = $id;
        if (! empty($input['house_id'])) {
            $house = $houseRepo->findWithoutFail($input['house_id']);
            if (empty($house)) {
                return $this->sendError(trans('flash.api.not_found', ['model' => 'House']), 404);
            }
        }

        $input['wechat_user_id'] = $GLOBALS['wx_user_session']['wechat_user_id'];
        $channelOrders = $channelOrderRepo->addChannelOrder($input);

        return $this->sendResponse($channelOrders->toArray(), trans('flash.api.save_success', ['model' => 'Channel Order']));
    }

    public function indexOrders($id, Request $request, ChannelOrderRepository $channelOrderRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channelOrderRepo->pushCriteria(new RequestCriteria($request));
        $channelOrderRepo->pushCriteria(new LimitOffsetCriteria($request));
        $channelOrders = $channelOrderRepo->getUserOrders($id, $request->all());
        $channelOrderRepo->resetUnread($id);

        return $this->sendResponse($channelOrders, trans('flash.api.retrieve_success', ['model' => 'Channel Orders']));
    }

    public function indexNewOrders($id, Request $request, ChannelOrderRepository $channelOrderRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channelOrderRepo->pushCriteria(new RequestCriteria($request));
        $channelOrderRepo->pushCriteria(new LimitOffsetCriteria($request));
        $channelOrders = $channelOrderRepo->getChannelOrders($id, $request->all());
        return $this->sendResponse($channelOrders, trans('flash.api.retrieve_success', ['model' => 'Channel Orders']));
    }

    public function showOrder($id, $orderId, Request $request, ChannelOrderRepository $channelOrderRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channelOrder = $channelOrderRepo->findWithoutFail($orderId);
        if (empty($channelOrder)) {
            return $this->sendError(trans('flash.api.not_found', ['model'=>'Channel Order']), 404);
        }

        $order = $channelOrderRepo->getUserOrderForChannel($orderId, $id, $request->all());
        return $this->sendResponse($order->toArray(), trans('flash.api.retrieve_success', ['model' => 'Channel Order']));
    }

    public function indexUsers($id, Request $request, ChannelOrderRepository $channelOrderRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $users = $channelOrderRepo->getChannelUsers($id, $request->all());
        return $this->sendResponse($users, trans('flash.api.retrieve_success', ['model' => 'Channel Orders']));
    }

    public function updateUser($id,
        $wechatUserId,
        Request $request,
        WechatUserRepository $wechatUserRepo,
        ChannelUserRepository $channelUserRepo)
    {
        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $wechatUser = $wechatUserRepo->findWithoutFail($wechatUserId);
        if (empty($wechatUser)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Wechat User']), 404);
        }

        $input = $request->all();
        if (empty($input['status']))
        {
            return $this->sendError('status 不存在');
        }

        $fields['channel_id'] = $id;
        $fields['wechat_user_id'] = $wechatUserId;
        $channelUser = $channelUserRepo->updateOrCreate($fields, $input + $fields);
        return $this->sendResponse($channelUser->toArray(), trans('flash.api.retrieve_success', ['model' => 'Channel User']));
    }

    public function indexItems($id, Request $request, ItemRepository $itemRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $items = $itemRepo->getItemsForChannel($id, $request->all());
        return $this->sendResponse($items->toArray(), trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function showItem($id, $itemId, Request $request, ItemRepository $itemRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $items = $itemRepo->getItemForChannel($itemId, $id, $request->all());
        return $this->sendResponse($items->toArray(), trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function indexUserItems($id,
        $wechatUserId,
        Request $request,
        WechatUserRepository $wechatUserRepo,
        ChannelUserItemRepository $channelUserItemRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $user = $wechatUserRepo->findWithoutFail($wechatUserId);
        if (empty($user)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Wechat User']), 404);
        }

        $this->validate($request, [
            'country' => 'required|integer'
        ]);

        $input = $request->all();
        $channelUserItems = $channelUserItemRepo->getChannelUserItems($id, $wechatUserId, $input);
        return $this->sendResponse($channelUserItems, trans('flash.api.retrieve_success', ['model' => 'Channel User Items']));
    }

    public function storeManagers($id,
        CreateChannelManagerAPIRequest $request,
        WechatUserRepository $wechatUserRepo,
        ChannelManagerRepository $channelManagerRepo)
    {
        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $input = $request->all();
        $user = $wechatUserRepo->getUserByUnionid($input['unionid']);
        if (empty($user)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Wechat User']), 404);
        }

        $exists = $channelManagerRepo->managerExists($id, $user->id);
        if ( ! empty($exists))
        {
            return $this->sendError('该渠道已有管理员或该账号已绑定渠道管理员', 422);
        }

        $manager = $channelManagerRepo->create(['channel_id' => $id, 'wechat_user_id' => $user->id]);
        return $this->sendResponse($manager->toArray(), trans('flash.api.save_success', ['model' => 'Channel Manager']));
    }

    public function destroyManagers($id, $unionid,
        WechatUserRepository $wechatUserRepo,
        ChannelManagerRepository $channelManagerRepo)
    {
        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $user = $wechatUserRepo->getUserByUnionid($unionid);
        if (empty($user)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Wechat User']), 404);
        }

        $exists = $channelManagerRepo->managerExists($id, $user->id);
        if (empty($exists))
        {
            return $this->sendError('该渠道未设置管理员或该账号已未绑定渠道管理员', 422);
        }

        $exists->forceDelete();

        return $this->sendResponse($id, trans('flash.api.delete_success', ['model' => 'Channel Manager']));
    }

    public function showIndex($id, Request $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channel = $this->channelRepository->getChannelIndex($id);
        return $this->sendResponse($channel, trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function storeItemCooperations($id, $itemId, Request $request, ItemRepository $itemRepo, CooperationRepository $cooperationRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $item = $itemRepo->findWithoutFail($itemId);
        if (empty($item)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Item']), 404);
        }

        $cooperation = $cooperationRepo->getByChannelIdAndItemId($id, $itemId);
        if ($cooperation)
        {
            if ($cooperation->apply_from == Cooperation::APPLY_FROM_CHANNEL)
            {
                return $this->sendError('已提交过合作申请');
            }
            else
            {
                return $this->sendError('项目方已提交过合作申请');
            }
        }

        $input = [
            'channel_id' => $id,
            'item_id' => $itemId,
            'apply_from' => Cooperation::APPLY_FROM_CHANNEL
        ];
        $cooperations = $cooperationRepo->create($input);
        return $this->sendResponse($cooperations->toArray(), trans('flash.api.save_success', ['model' => 'Cooperation']));
    }

    public function updateItemCooperations($id, $itemId, Request $request, ItemRepository $itemRepo, CooperationRepository $cooperationRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $item = $itemRepo->findWithoutFail($itemId);
        if (empty($item)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Item']), 404);
        }

        $cooperation = $cooperationRepo->getByChannelIdAndItemId($id, $itemId);
        if ( ! $cooperation || $cooperation->apply_from == Cooperation::APPLY_FROM_CHANNEL)
        {
            return $this->sendError('该项目方未提交过合作申请');
        }
        elseif ($cooperation->status != Cooperation::STATUS_DEFAULT)
        {
            return $this->sendError('该请求已经处理');
        }

        if ($request->input('agree', 0))
        {
            $cooperation->status = Cooperation::STATUS_SUCCESS;
            $cooperation->save();

            return $this->sendResponse($cooperation->toArray(), trans('flash.api.save_success', ['model' => 'Cooperation']));
        }
        elseif ($request->input('refused', 0))
        {
            $cooperation->forceDelete();
            return $this->sendResponse([], '拒绝合作成功');
        }

        return $this->sendError('参数有误');
    }

    public function storeItemOpens($id, $itemId, Request $request,
        ItemRepository $itemRepo,
        CooperationRepository $cooperationRepo,
        ChannelUserItemRepository $channelUserItemRepo,
        ChannelOrderRepository $channelOrderRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $this->validate($request, [
            'wechat_user_id' => 'required',
        ]);

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $item = $itemRepo->findWithoutFail($itemId);
        if (empty($item)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Item']), 404);
        }

        $cooperation = $cooperationRepo->getByChannelIdAndItemId($id, $itemId);
        if ( ! $cooperation || $cooperation->status == Cooperation::STATUS_DEFAULT)
        {
            return $this->sendError('未与该项目方建立合作');
        }
        elseif ($cooperation->status == Cooperation::STATUS_OPEN)
        {
            return $this->sendError('已经开放给该项目方');
        }

        $cooperation->status = Cooperation::STATUS_OPEN;
        $cooperation->save();

        $input = [
            'channel_id' => $id,
            'wechat_user_id' => $request->input('wechat_user_id'),
            'item_id' => $itemId
        ];
        $channelUserItemRepo->firstOrCreate($input);

        $channelOrderRepo->pushUserToItem($id, $itemId, $request->input('wechat_user_id'));

        return $this->sendResponse($cooperation->toArray(), trans('flash.api.save_success', ['model' => 'Cooperation']));
    }

    public function showVisitDays($id, Request $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $days = $this->channelRepository->getVisitDays($id);
        return $this->sendResponse($days, trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function showVisitUsers($id, Request $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $days = $this->channelRepository->getVisitUsers($id, $request->all());
        return $this->sendResponse($days, trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function showRelayDays($id, Request $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $days = $this->channelRepository->getRelayDays($id);
        return $this->sendResponse($days, trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function showRelayUsers($id, Request $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $days = $this->channelRepository->getRelayUsers($id, $request->all());
        return $this->sendResponse($days, trans('flash.api.retrieve_success', ['model' => 'Channel']));
    }

    public function storeOrderRecommend($id, $orderId, Request $request,
        ChannelOrderRepository $channelOrderRepo,
        CooperationRepository $cooperationRepo,
        ItemOrderRepository $itemOrderRepo)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $this->validate($request, [
            'item_id' => 'required'
        ]);
        $input = $request->all();

        $channel = $this->channelRepository->findWithoutFail($id);
        if (empty($channel)) {
            return $this->sendError(trans('flash.api.not_found', ['model' => 'Channel']), 404);
        }

        $channelOrder = $channelOrderRepo->findWithoutFail($orderId);
        if (empty($channelOrder)) {
            return $this->sendError(trans('flash.api.not_found', ['model'=>'Channel Order']), 404);
        }

        $cooperation = $cooperationRepo->getByChannelIdAndItemId($id, $input['item_id']);
        if ( ! $cooperation || $cooperation->status == Cooperation::STATUS_DEFAULT)
        {
            return $this->sendError('未与该项目方建立合作');
        }

        $itemOrder = [
            'item_id' => $input['item_id'],
            'channel_id' => $id,
            'channel_order_id' => $orderId,
            'house_id' => $channelOrder->house_id,
            'wechat_user_id' => $channelOrder->wechat_user_id,
            'consult_content' => $channelOrder->consult_content
        ];
        $itemOrders = $itemOrderRepo->create($itemOrder);
        return $this->sendResponse($itemOrders->toArray(), trans('flash.api.save_success', ['model' => 'Item Order']));
    }
}
